<template>
    <!-- 物联设备维护 -->
    <div>
        <el-row type="flex" justify="space-between">
            <el-form class="serach-form" ref="searchForm" :model="searchForm" :inline="true" @submit.native.prevent>
                <el-form-item>
                    <el-select filterable v-model="searchForm.organizationId" @change="orgChange" placeholder="请选择业主单位">
                        <el-option
                            v-for="item in orgList"
                            :key="item.organizationId"
                            :label="item.shortName"
                            :value="item.organizationId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-select @change="search" filterable v-model="searchForm.serverId" placeholder="请选择通信服务器">
                        <el-option label="全部通信服务器" value=""></el-option>
                        <el-option
                        v-for="item in typeList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.serverId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-input
                        placeholder="请输入探测器名称"
                        v-model="searchForm.name"
                        @keyup.enter.native="search"
                        clearable>
                    </el-input>
                </el-form-item>
                <el-form-item>
                    <el-button class="form-search-btn" type="primary" @click="search">查询</el-button>
                </el-form-item>
            </el-form>
            <div class="more-btns">
                <el-button class="form-search-btn" style="margin-right:10px;" @click="unenteredEquipment" type="primary">查看未录入设备</el-button>
                <el-dropdown @command="handleCommand">
                    <span class="el-dropdown-link">更多操作</span>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="add">新增</el-dropdown-item>
                        <el-dropdown-item command="download">下载模板</el-dropdown-item>
                        <el-dropdown-item command="import">导入</el-dropdown-item>
                        <el-dropdown-item command="normalDelete">批量删除</el-dropdown-item>
                        <el-dropdown-item command="perfectDelete">批量彻底删除</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
        </el-row>
        <div>
            <el-table
                v-loading="loading"
                ref="singleUnitTableList"
                :data="tableData"
                style="width: 100%"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="50"></el-table-column>
                <el-table-column label="序号" type="index" width="50"></el-table-column>
                <el-table-column label="图片" prop="fcfacilitiesPicUrl" width="120">
                    <template v-if="scope.row.fcfacilitiesPicUrl != ''" slot-scope="scope">
                        <img :src="scope.row.fcfacilitiesPicUrl.split(',')[0]" width="50px" height="50px" @click="$imgPreview" :data-imgpreview="scope.row.fcfacilitiesPicUrl">
                    </template>
                </el-table-column>
                <el-table-column label="所属通信服务器" prop="serverName"></el-table-column>
                <el-table-column label="名称" prop="name"></el-table-column>
                <el-table-column label="系统类型" prop="fireSystemTypeName"></el-table-column>
                <el-table-column label="具体位置" prop="levelLocation"></el-table-column>
                <el-table-column label="备注" prop="remarks"></el-table-column>
                <el-table-column label="操作" width="180">
                    <template slot-scope="scope">
                        <el-button v-if="showType != 1" @click="showSon(scope.row)" type="text" size="small">子集</el-button>
                        <span v-if="showType != 1" class="dividing-line">|</span>
                        <el-button @click="editFireStation(scope.row)" type="text" size="small">编辑</el-button>
                        <span class="dividing-line">|</span>
                        <el-button @click="normalDelete(scope.row)" type="text" size="small">删除</el-button>
                        <span class="dividing-line">|</span>
                        <el-button @click="perfectDelete(scope.row)" type="text" size="small">彻底</el-button>
                    </template>
                </el-table-column>
                <el-table-column type="expand" width='1'>
                    <template slot-scope="scope">
                        <subset-table :rowInfo="scope.row" :serverTypeList="typeList"></subset-table>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                background
                @current-change="handleCurrentChange"
                @size-change="handleSizeChange"
                :current-page.sync="currentPage"
                :page-sizes="[10, 50, 100]"
                :page-size="10"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>
        <el-drawer
        title="未录入设备"
        :visible.sync="unenteredEquipmenttc"
        >
            <unentered-equipment ref="unenteredEquipment" @child-event='parentEvent' :unenteredEquipment='unenteredEquipment' :addFcfacilities='addFcfacilities'></unentered-equipment>
        </el-drawer>
        <!-- 新增/编辑弹框 -->
        <el-dialog
            :close-on-click-modal="false"
            :title="dialogTitle"
            width="800px"
            top='5vh'
            v-if="dialogBaseInfo"
            :visible.sync="dialogBaseInfo"
            @close="closeBaseInfo"
            v-dialogDrag>
            <fire-service-mainten :organizationId="searchForm.organizationId" isTop="1" :serverId="searchForm.serverId" :serverTypeList="typeList" :oldInfo="baseInfo" :closeFun="closeBaseInfo"></fire-service-mainten>
        </el-dialog>
        <!-- 下载模板 -->
        <el-dialog
            :close-on-click-modal="false"
            title="下载模板"
            width="1000px"
            top='15vh'
            v-if="dialogDownLoad"
            :visible.sync="dialogDownLoad"
            @close="closeDownLoad"
            v-dialogDrag>
            <down-load-temp :organizationId="searchForm.organizationId" :closeFun="closeDownLoad"></down-load-temp>
        </el-dialog>
        <!-- 导入模板 -->
        <el-dialog
            :close-on-click-modal="false"
            title="导入模板"
            width="600px"
            top='15vh'
            v-if="dialogImportRefresh"
            :visible.sync="dialogImport"
            @close="closeImport"
            v-dialogDrag>
            <import-temp :organizationId="searchForm.organizationId" :organizationName="searchForm.organizationName" :closeFun="closeImport" ref="importTemp"></import-temp>
        </el-dialog>
    </div>
</template>
<script>
import { getOrgList } from '@/api/org'
import { getServerIdListData, getFcfList, delAssignFcf, delLogiAssignFcf } from '@/api/sysConfig'
import { stopImportFTemplate } from '@/api/fcf'
import SubsetTable from './SubsetTable'
import FireServiceMainten from '../Dialog/FireServiceMainten'
import DownLoadTemp from '../Dialog/DownLoadTemp'
import ImportTemp from '../Dialog/ImportTemp'
import UnenteredEquipment from '../Dialog/UnenteredEquipment'

var loadingObj = null
export default {
    name: 'FireFacstruct',
    props: {
        // 展示形式 0：层级视图 1：清单视图
        showType: {
            required: true,
            default() {
                return 0
            }
        }
    },
    components: {
        SubsetTable,
        FireServiceMainten,
        DownLoadTemp,
        ImportTemp,
        UnenteredEquipment
    },
    data() {
        return {
            loading: false,
            orgList: [],
            typeList: [],
            searchForm: {
                organizationId: '',
                organizationName: '',
                serverId: '',
                name: ''
            },
            tableData: [],
            // 分页
            currentPage: 1,
            pageSize: 10,
            total: 0,
            selectedFireDevices: [], // 勾选的消防设备
            // 新增/编辑弹框
            dialogTitle: '',
            dialogBaseInfo: false,
            baseInfo: {},
            // 下载模板
            dialogDownLoad: false,
            // 导入模板
            dialogImport: false,
            // 是否需要刷新导入弹框
            dialogImportRefresh: false,
            // 未录入设备弹窗
            unenteredEquipmenttc:false,
            isUnenteredEquipment:false,
        }
    },
    created() {
        let that = this
        // 获取业主单位信息
        getOrgList({
            queryType: 0
        }).then(res => {
            if(res.status = 200) {
                that.orgList = res.data
                // 初始选中第一个单位
                that.searchForm.organizationId = res.data[0].organizationId
                that.searchForm.organizationName = res.data[0].shortName
            }
        })
        if(that.$route.params.windowing){
            that.unenteredEquipmenttc = true
        }else{
            that.unenteredEquipmenttc = false
        }
    },
    methods: {
        getTypeList(orgId) {
            let that = this
            if(that.$route.params.organizationId){
                that.searchForm.organizationId = that.$route.params.organizationId
            }
            let parames = {
                organizationId: that.searchForm.organizationId,
                pageIndex: 0,
                pageSize: 1000
            }
            getServerIdListData(parames).then(res => {
                if(res.status === 200) {
                    that.typeList = res.data
                    // 初始选中第一个单位
                    // that.searchForm.serverId = res.data.length > 0 ? res.data[0].serverId : ''
                    // 加载列表
                    that.getTableData()
                }
            })
        },
        // 单位切换
        orgChange(val) {
            if(val) {
                for(let i=0, len=this.orgList.length; i < len; i++) {
                    // 找出对应单位id的中文名称
                    if(this.orgList[i].organizationId == val) {
                        this.searchForm.organizationName = this.orgList[i].shortName
                        return false
                    }
                }
            }
        },
        parentEvent(data){
            let that = this
            if(that.$route.params.organizationId){
                that.searchForm.organizationId = that.$route.params.organizationId
            }else{
                that.searchForm.organizationId = data.orgId
            }
        },
        getTableData(pageIndex, pageSize) {
            let that = this
            that.loading = true
            if (pageIndex) {
                that.currentPage = pageIndex
            }
            if (pageSize) {
                that.pageSize = pageSize
            }
            let parames = {
                organizationId : that.searchForm.organizationId,
                serverId : that.searchForm.serverId,
                parentId : 0,
                name: that.searchForm.name.trim(),
                pageIndex : that.currentPage - 1,
                pageSize : that.pageSize,
                queryType : 1,
                showType: that.showType
            }
            // 获取列表信息
            getFcfList(parames).then(res => {
                that.tableData = res.data
                that.total = res.total
                that.loading = false
            })
        },
        handleSizeChange(pageSize) {
            this.getTableData(1, pageSize)
        },
        handleCurrentChange(currentPage) {
            this.getTableData(currentPage)
        },
        search() {
            this.getTableData(1)
        },
        // 多选
        handleSelectionChange(val) {
            this.selectedFireDevices = val
        },
        // 更多操作
        handleCommand(command) {
            let that = this

            switch (command) {
                case 'add':
                    that.addFcfacilities()
                    return false
                case 'import':
                    that.importList()
                    return false
                case 'download':
                    that.downloadTemp()
                    return false
                case 'normalDelete':
                    that.batchDelete(1)
                    return false
                case 'perfectDelete':
                    that.batchDelete(2)
                    return false
                default:
                    return false
            }
        },
        // 新增
        addFcfacilities() {
            let that = this
            that.baseInfo = {}
            that.dialogBaseInfo = true
        },
        closeBaseInfo(flag) {
            let that = this
            that.dialogBaseInfo = false
            if(flag) {
                that.getTableData(this.baseInfo.id?'':1)
            }
        },
        // 导入
        importList() {
            this.dialogImportRefresh = true
            this.dialogImport = true
        },
        closeImport(flag) {
            let that = this
            // 获取是否需要回滚标记结果
            let needBackFlag = that.$refs.importTemp.getNeedBackFlag()
            that.dialogImport = false
            // 导入过程取消，需要回滚
            if(needBackFlag) {
                // 弹出确认框
                this.$confirm("确定取消吗？", '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    roundButton: true
                }).then(() => {
                    // 关闭导入弹框
                    that.dialogImportRefresh = false
                    loadingObj = that.$loading({
                        lock: true,
                        text: "数据回滚中，请稍等...",
                        spinner: "el-icon-loading",
                        background: "rgba(0, 0, 0, 0.7)"
                    })
                    // 调用回滚接口
                    stopImportFTemplate({
                        redisKey: needBackFlag
                    }).then(res => {
                        loadingObj.close()
                        if(res.status === 200) {
                            that.$message({
                                type: 'success',
                                message: '取消导入成功!'
                            })
                        } else {
                            that.$message({
                                type: 'warning',
                                message: res.info
                            })
                        }
                    })
                }).catch(() => {
                    that.dialogImport = true
                    // 继续导入
                    that.$refs.importTemp.goOnImport()
                })
            } else {
                that.dialogImportRefresh = false
                if(flag) {
                    that.getTableData()
                }
            }
            
        },
        // 下载模板
        downloadTemp() {
            this.dialogDownLoad = true
        },
        closeDownLoad() {
            this.dialogDownLoad = false
        },
        // 批量删除 type: 1-批量删除  2-批量彻底删除
        batchDelete(type) {
            let that = this
            let ids = []
            // 获取勾选的数据
            for(let i=0, len=that.selectedFireDevices.length; i < len; i++) {
                ids.push(that.selectedFireDevices[i].id)
            }
            if(ids.length > 0) {
                let tips = ''
                const batchDeleteLoading = that.$loading({
                    lock: true,
                    text: '批量删除中，请稍等...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                if(that.showType === 1) {
                    // 清单视图
                    if(type === 1) {
                        tips = '请确定是否批量删除数据？'
                    } else {
                        tips = '请确定是否批量彻底删除数据？删除后，数据无法恢复。'
                    }
                } else {
                    // 层级视图
                    if(type === 1) {
                        tips = '请确定是否批量删除数据？注意：下级数据会一并删除。'
                    } else {
                        tips = '请确定是否批量彻底删除数据？删除后，数据无法恢复。注意：下级数据会一并删除。'
                    }
                }
                
                that.$confirm(tips, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    roundButton: true
                }).then(() => {
                    if(type === 1) {
                        // 删除
                        delLogiAssignFcf({
                            organizationId: that.searchForm.organizationId,
                            ids: ids.join(',')
                        }).then(res => {
                            if(res.status === 200) {
                                that.$message({
                                    type: 'success',
                                    message: '删除成功!'
                                })
                                batchDeleteLoading.close()
                                that.getTableData()
                            }
                        })
                    } else {
                        // 彻底删除
                        delAssignFcf({
                            organizationId: that.searchForm.organizationId,
                            ids: ids.join(',')
                        }).then(res => {
                            if(res.status === 200) {
                                that.$message({
                                    type: 'success',
                                    message: '删除成功!'
                                })
                                batchDeleteLoading.close()
                                that.getTableData()
                            }
                        })
                    }
                }).catch(() => {
                    batchDeleteLoading.close()
                })
            } else {
                that.$message({
                    type: 'warning',
                    message: '请勾选你要删除的物联设备!'
                })
            }
        },
        // 展开子集
        showSon(row) {
            this.$refs.singleUnitTableList.toggleRowExpansion(row)
        },
        // 编辑
        editFireStation(row) {
            let that = this
            that.baseInfo = row
            // 显示弹框
            that.dialogBaseInfo = true
        },
        // 删除
        normalDelete(row) {
            // 阻止事件冒泡
            event.stopPropagation()
            let that = this
            const loading = this.$loading({
                lock: true,
                text: '删除中，请稍等...',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            if (row) {
                this.$confirm('确认删除该设备吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    roundButton: true
                }).then(() => {
                    delLogiAssignFcf({
                        organizationId: that.searchForm.organizationId,
                        ids: row.id
                    }).then(res => {
                        if(res.status === 200) {
                            that.$message({
                                type: 'success',
                                message: '删除成功!'
                            })
                            loading.close()
                            that.getTableData()
                        }
                    })
                }).catch(() => {
                    loading.close()
                })
            }
        },
        // 彻底删除
        perfectDelete(row) {
            // 阻止事件冒泡
            event.stopPropagation()
            let that = this
            if (row) {
                this.$confirm('确认彻底删除该设备吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    roundButton: true
                }).then(() => {
                    delAssignFcf({
                        organizationId: that.searchForm.organizationId,
                        ids: row.id
                    }).then(res => {
                        if(res.status === 200) {
                            that.$message({
                                type: 'success',
                                message: '删除成功!'
                            })
                            that.getTableData()
                        }
                    })
                }).catch(() => {})
            }
        },
        // 未录入设备弹窗
        unenteredEquipment(){
            let _this = this
            _this.unenteredEquipmenttc = !_this.unenteredEquipmenttc
            if(_this.isUnenteredEquipment){
                _this.$refs.unenteredEquipment.noenterDeviceList()
            }
            _this.isUnenteredEquipment = true
        }
    },
    watch: {
        orgIdSelect(val, oldVal) {
            if(val && val !== oldVal) {
                this.searchForm.serverId = ''
                this.getTypeList(val)
            }
        },
        '$store.state.listQueryParam'(val){
            if(this.$router.currentRoute.name=='fireFacstruct'){
                this.searchForm.organizationId = val.organizationId||''
                // this.unenteredEquipmenttc=val.windowing
            }
        }
    },
    computed: {
        orgIdSelect() {
            return this.searchForm.organizationId
        },
    }
}
</script> 
